package cordoba.application
{
    import cordoba.domain.AbstractItems;
    import cordoba.domain.Plan;
    import cordoba.domain.Plans;
    import cordoba.domain.Process;
    import cordoba.domain.Processes;
    
    import mx.collections.ArrayCollection;
    import mx.rpc.AsyncToken;
    import mx.rpc.http.mxml.HTTPService;

    public class GetConfigurationCommand
    {
        [Inject]
        public var service:HTTPService;
        
        [Inject]
        public var processes:Processes;
        
        [Inject]
        public var plans:Plans;
        
        public function execute(event:GetConfigurationEvent):AsyncToken {
            return service.send() as AsyncToken;
        }
        
        public function result(obj:Object):void {
            buildItems(
                processes,
                obj.tamavo.processes.process as ArrayCollection,
                getBuildProcessCallback()
            );
            buildItems(
                plans,
                obj.tamavo.plans.plan as ArrayCollection,
                getBuildPlansCallback()
            );
        }
        
        private function buildItems(items:AbstractItems, source:ArrayCollection,
                                    buildCallback:Function):void {
            var ac:ArrayCollection = new ArrayCollection();
            for each (var o:Object in source) {
                ac.addItem(buildCallback(o));
            }
            items.add(ac);
        }
        
        private function getBuildProcessCallback():Function {
            return function(o:Object):Process {
                var process:Process = new Process();
                process.idProcess = o.id;
                process.arguments = o.arguments;
                process.command = o.command;
                process.name = o.name;
                return process;
            };
        }
        
        private function getBuildPlansCallback():Function {
            return function(o:Object):Plan {
                var plan:Plan = new Plan();
                plan.idPlan = o.id;
                plan.name = o.name;
                plan.processes = String(o.processes).split(',');
                return plan;
            };
        }
    }
}